package com.iocup.keybastion.core.matching.impl;

import com.iocup.keybastion.context.WebContextHolder;
import com.iocup.keybastion.core.matching.Matcher;
import com.iocup.keybastion.core.matching.MatchingChecker;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 匹配检测器
 * @author xyjxust
 * @create 2022/3/1 17:29
 **/
@Slf4j
public class DefaultMatchingChecker implements MatchingChecker {
    /**
     * 匹配器集合
     */
    private Map<String, Matcher> matcherHashMap = new HashMap<>();

    /**
     * 添加请求匹配器
     *
     * @param matchers 匹配器
     * @return 对象自身
     */
    @Override
    public MatchingChecker addMatcher(Matcher... matchers) {
        Arrays.asList(matchers).stream().forEach(m->matcherHashMap.put(m.getType(),m));
        return this;
    }

    @Override
    public boolean matches(WebContextHolder webContextHolder) {
        if (!matcherHashMap.isEmpty()) {
            for (final Matcher matcher : matcherHashMap.values()) {
                final boolean matches = matcher.matches(webContextHolder);
                log.debug("Checking matcher: {} -> {}", matcher, matches);
                //当其中匹配器有一个返回false，那么就打断循环，返回false
                if (!matches) {
                    return false;
                }
            }
        }
        return true;
    }

}
